package com.kuaiyin.controller.user;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.kuaiyin.dto.LoginDTO;
import com.kuaiyin.result.Result;
import com.kuaiyin.service.IUserService;
import com.kuaiyin.utils.RedisUtils;
import com.kuaiyin.vo.CaptchaVO;
import com.kuaiyin.vo.LoginVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

@Slf4j
@Tag(name = "登录/登出")
@RestController
@RequestMapping("/user")
public class LoginController {
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisUtils redisUtils;

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result<LoginVO> login(@RequestBody @Validated LoginDTO loginDTO) {
        LoginVO loginvo = userService.login(loginDTO);
        return Result.success(loginvo);
    }

    @Operation(summary = "获取验证码")
    @GetMapping("/captcha/base64")
    public Result<CaptchaVO> getCaptchaBase64(@RequestParam String uuid) throws IOException {
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(200, 80, 4, 20);

        // 写入字节数组
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        captcha.write(outputStream);

        // 编码成 Base64
        byte[] bytes = outputStream.toByteArray();
        String base64Image = Base64.getEncoder().encodeToString(bytes);

        // 构造响应对象
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setImage(base64Image);

        // 存储到 Redis
        String key = "captcha:" + uuid;
        redisUtils.set(key, captcha.getCode());
        redisUtils.expire(key, 30);
        return Result.success(captchaVO);
    }
}
